package sk.pitonak.mhd.ui;

import sk.pitonak.mhd.R;
import sk.pitonak.mhd.TabsAdapter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.ActionMode;

public class MHDActivity extends FragmentActivity {
	private static final int TAB_DEFAULT = 1;

	private ActionBar mActionBar;
	private ViewPager mViewPager;
	private TabsAdapter mTabsAdapter;

	private ActionMode mActionMode;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mActionBar = getSupportActionBar();
		mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		mViewPager = (ViewPager) findViewById(R.id.pager);
		mTabsAdapter = new TabsAdapter(this, mActionBar, mViewPager);

		mTabsAdapter.addTab(R.string.history, HistoryFragment.class);
		mTabsAdapter.addTab(R.string.search, SearchFragment.class);

		selectTab(TAB_DEFAULT);
	}

	@Override
	protected void onResume() {
		super.onResume();
		mViewPager.setCurrentItem(TAB_DEFAULT, false);
	}

	protected void selectTab(int position) {
		if(position >= mActionBar.getTabCount()) return;
		mActionBar.getTabAt(position).select();
		mViewPager.setCurrentItem(position);
	}

	@Override
	public void onActionModeStarted(ActionMode mode) {
		mActionMode = mode;
		super.onActionModeStarted(mode);
	}

	@Override
	public void onActionModeFinished(ActionMode mode) {
		mActionMode = null;
		super.onActionModeFinished(mode);
	}

	@Override
	public void onBackPressed() {
		if(mActionMode != null) {
			mActionMode.finish();
			mActionMode = null;
		}
		else if(mActionBar.getSelectedTab().getPosition() != TAB_DEFAULT) {
			selectTab(TAB_DEFAULT);
		}
		else {
			super.onBackPressed();
		}
	}
}
